#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2023/04/12
# @Author  : Tuut
# @Email   : 49616026@qq.com
# @File    : MyRedisFactory.py
import json

import redis as redis


# ***
# 参考文献:
# https://www.runoob.com/redis/lists-lindex.html
# https://www.runoob.com/redis/redis-lists.html
class RedisConfig:
    RedisDb = dict(host="", passwd="", port=0)
    conn = {}

    def __init__(self, host, passwd, port):
        self.RedisDb = dict(host=host, passwd=passwd, port=port)
        self.host = host
        self.passwd = passwd
        self.port = port

    def get_pool(self) -> conn:
        # 连接业务数据库
        pool = redis.ConnectionPool(host=self.host,
                                    port=self.port,
                                    password=self.passwd)
        self.conn = redis.Redis(connection_pool=pool)
        return self.conn

    def put_array(self, key, val):
        try:
            self.conn.lpush(key, val)
            self.conn.expire(key, 60 * 60)
        except Exception as e:
            print(e)

    def put_array_intimes(self, key, val, inTimes):
        try:
            self.conn.lpush(key, val)
            self.conn.expire(key, inTimes)
        except Exception as e:
            print(e)

    def get_val(self, key, json_flg=True):
        try:
            val = self.conn.get(key)
            if val is None:
                return None
            if json_flg:
                return json.loads(val)
            return val
        except Exception as e:
            print(e)

    def push_val(self, key, val, json_flg):
        if json_flg:
            str_val = json.dumps(val, ensure_ascii=False)
        else:
            str_val = val
        self.conn.set(key, str_val)

    def push_val_intimes(self, key, val, json_flg, inTimes):
        if json_flg:
            str_val = json.dumps(val, ensure_ascii=False)
        else:
            str_val = val
        self.conn.set(key, str_val)
        self.conn.expire(key, inTimes)

    def set_val(self, key, val, json_flg):
        if json_flg:
            str_val = json.dumps(val, ensure_ascii=False)
        else:
            str_val = val
        self.conn.set(key, str_val)

    def del_val(self, key):
        self.conn.delete(key)

    def set_val_intimes(self, key, val, json_flg, inTimes):
        if json_flg:
            str_val = json.dumps(val, ensure_ascii=False)
        else:
            str_val = val
        self.conn.set(key, str_val)
        self.conn.expire(key, inTimes)
